package cn.com.shadowless.xinning.view.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mengpeng.mphelper.ToastUtils;

import java.util.List;

import butterknife.BindView;
import cn.com.shadowless.xinning.MyApplication;
import cn.com.shadowless.xinning.R;
import cn.com.shadowless.xinning.callback.RequestCallBack;
import cn.com.shadowless.xinning.model.RequestResult;
import cn.com.shadowless.xinning.model.order.MaintenanceOrderInfo;
import cn.com.shadowless.xinning.presenter.OrderPresenter;
import cn.com.shadowless.xinning.utils.PreferencesUtils;
import cn.com.shadowless.xinning.view.BaseFragment;

/**
 * The type Maintenance fragment.
 *
 * @author sHadowLess
 */
public class MaintenanceFragment extends BaseFragment {

    /**
     * The Maintenance receipt info receipt num.
     */
    @BindView(R.id.maintenance_receiptInfo_ReceiptNum)
    TextView maintenanceReceiptInfoReceiptNum;
    /**
     * The Maintenance receipt info make time.
     */
    @BindView(R.id.maintenance_receiptInfo_MakeTime)
    TextView maintenanceReceiptInfoMakeTime;
    /**
     * The Maintenance receipt info maker.
     */
    @BindView(R.id.maintenance_receiptInfo_Maker)
    TextView maintenanceReceiptInfoMaker;
    /**
     * The Maintenance receipt info making depart.
     */
    @BindView(R.id.maintenance_receiptInfo_MakingDepart)
    TextView maintenanceReceiptInfoMakingDepart;
    /**
     * The Maintenance receipt info position job.
     */
    @BindView(R.id.maintenance_receiptInfo_PositionJob)
    TextView maintenanceReceiptInfoPositionJob;
    /**
     * The Maintenance app info apply order.
     */
    @BindView(R.id.maintenance_appInfo_ApplyOrder)
    TextView maintenanceAppInfoApplyOrder;
    /**
     * The Maintenance app info apply date.
     */
    @BindView(R.id.maintenance_appInfo_ApplyDate)
    TextView maintenanceAppInfoApplyDate;
    /**
     * The Maintenance app info apply depart.
     */
    @BindView(R.id.maintenance_appInfo_ApplyDepart)
    TextView maintenanceAppInfoApplyDepart;
    /**
     * The Maintenance app info applier.
     */
    @BindView(R.id.maintenance_appInfo_Applier)
    TextView maintenanceAppInfoApplier;
    /**
     * The Maintenance app info machine name.
     */
    @BindView(R.id.maintenance_appInfo_MachineName)
    TextView maintenanceAppInfoMachineName;
    /**
     * The Maintenance app info fix type.
     */
    @BindView(R.id.maintenance_appInfo_FixType)
    TextView maintenanceAppInfoFixType;
    /**
     * The Maintenance app info machine code.
     */
    @BindView(R.id.maintenance_appInfo_MachineCode)
    TextView maintenanceAppInfoMachineCode;
    /**
     * The Maintenance app info warranty type.
     */
    @BindView(R.id.maintenance_appInfo_WarrantyType)
    TextView maintenanceAppInfoWarrantyType;
    /**
     * The Maintenance app info last number.
     */
    @BindView(R.id.maintenance_appInfo_LastNumber)
    TextView maintenanceAppInfoLastNumber;
    /**
     * The Maintenance app info now number.
     */
    @BindView(R.id.maintenance_appInfo_NowNumber)
    TextView maintenanceAppInfoNowNumber;
    /**
     * The Maintenance app info error description.
     */
    @BindView(R.id.maintenance_appInfo_ErrorDescription)
    TextView maintenanceAppInfoErrorDescription;
    /**
     * The Maintenance app info fix description.
     */
    @BindView(R.id.maintenance_appInfo_FixDescription)
    TextView maintenanceAppInfoFixDescription;
    /**
     * The Maintenance app info is temp.
     */
    @BindView(R.id.maintenance_appInfo_IsTemp)
    TextView maintenanceAppInfoIsTemp;
    /**
     * The Maintenance app info is cost.
     */
    @BindView(R.id.maintenance_appInfo_IsCost)
    TextView maintenanceAppInfoIsCost;
    /**
     * The Maintenance fix order check order.
     */
    @BindView(R.id.maintenance_fixOrder_CheckOrder)
    LinearLayout maintenanceFixOrderCheckOrder;
    /**
     * The Maintenance acceptance user depart.
     */
    @BindView(R.id.maintenance_acceptance_UserDepart)
    TextView maintenanceAcceptanceUserDepart;
    /**
     * The Maintenance acceptance confirm people.
     */
    @BindView(R.id.maintenance_acceptance_ConfirmPeople)
    TextView maintenanceAcceptanceConfirmPeople;
    /**
     * The Maintenance remark remark content.
     */
    @BindView(R.id.maintenance_remark_RemarkContent)
    TextView maintenanceRemarkRemarkContent;
    /**
     * The Maintenance other cost fix cost.
     */
    @BindView(R.id.maintenance_otherCost_FixCost)
    TextView maintenanceOtherCostFixCost;
    /**
     * The Maintenance check process.
     */
    @BindView(R.id.maintenance_check_Process)
    LinearLayout maintenanceCheckProcess;

    private final String url = "api/CareConfirmAppForm/LoadCheckHistory?%s=";
    private final String forMat = "%s\n预算总金额：%s\n已报销：%s\n报销中：%s\n剩余可报销：%s\n已申请未报销：%s\n在申请未报销：%s\n剩余可申请：%s";

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_maintenance_layout;
    }

    @Override
    protected void initData() {
        Bundle bundle = getArguments();
        if (null != bundle) {
            String orderId = bundle.getString("orderId");
            String userName = bundle.getString("userName");
            initMaintenanceOrderInfo(orderId, userName);
            initCheckHistoryList(String.format(url, "id") + orderId, mActivity, maintenanceCheckProcess);
        }
    }

    @Override
    protected void initView() {

    }

    private void initMaintenanceOrderInfo(String orderId, String userName) {
        OrderPresenter
                .getSingleton()
                .getMaintenanceOrderInfo(orderId, userName, new RequestCallBack<MaintenanceOrderInfo>() {
                    @Override
                    public void success(RequestResult<MaintenanceOrderInfo> result) {
                        String token = result.getLoginToken();
                        String oldToken = PreferencesUtils.getString(MyApplication.getInstance(), "token", "-1");
                        if (result.isSucceed() && null != result.getResult()) {
                            if (null != token && token.equals(oldToken)) {
                                Log.e(TAG, "success: " + result.toString());
                                MaintenanceOrderInfo.DataBean dataBean = result.getResult().getData();
                                MaintenanceOrderInfo.DataBean.CarePushAppFormBean carePushAppFormBean = dataBean.getCarePushAppForm();
                                MaintenanceOrderInfo.DataBean.CarePushAppFormBean.BudgetItemObjectBean budgetItemObjectBean = carePushAppFormBean.getBudgetItemObject();
                                MaintenanceOrderInfo.DataBean.CheckUserObjectBean checkUserObjectBean = dataBean.getCheckUserObject();
                                MaintenanceOrderInfo.DataBean.CreateUserObjectBean createUserObjectBean = dataBean.getCreateUserObject();
                                List<MaintenanceOrderInfo.DataBean.PersonListBean> personListBeans = dataBean.getPersonList();

                                String id = dataBean.getId();
                                String createTimeStr = dataBean.getCreateTimeStr();
                                String createUserName = dataBean.getCreateUserName();
                                String departmentName = createUserObjectBean.getDepartmentName();
                                String positionName = createUserObjectBean.getPositionName();
                                maintenanceReceiptInfoReceiptNum.setText(id);
                                maintenanceReceiptInfoMakeTime.setText(createTimeStr);
                                maintenanceReceiptInfoMaker.setText(createUserName);
                                maintenanceReceiptInfoMakingDepart.setText(departmentName);
                                maintenanceReceiptInfoPositionJob.setText(positionName);

                                String applyId = carePushAppFormBean.getId();
                                String careDateStr = carePushAppFormBean.getCareDateStr();
                                String applicantUserName = carePushAppFormBean.getApplicantUserName();
                                String name = carePushAppFormBean.getName();
                                String typeName = carePushAppFormBean.getTypeName();
                                String careNo = carePushAppFormBean.getCareNo();
                                String machineTypeName = dataBean.getTypeName();
                                String preMileage = getDecimal(dataBean.getPreMileage().doubleValue());
                                String nowMileage = getDecimal(dataBean.getNowMileage().doubleValue());
                                String explanation = dataBean.getExplanation();
                                String careContent = carePushAppFormBean.getCareContent();
                                boolean isTemp = dataBean.isTemp();
                                boolean isFree = dataBean.isFree();
                                maintenanceAppInfoErrorDescription.setText(careContent);
                                maintenanceAppInfoApplyOrder.setText(applyId);
                                maintenanceAppInfoApplyDate.setText(careDateStr);
                                maintenanceAppInfoApplyDepart.setText(departmentName);
                                maintenanceAppInfoApplier.setText(applicantUserName);
                                maintenanceAppInfoMachineName.setText(name);
                                maintenanceAppInfoFixType.setText(typeName);
                                maintenanceAppInfoMachineCode.setText(careNo);
                                maintenanceAppInfoWarrantyType.setText(machineTypeName);
                                maintenanceAppInfoLastNumber.setText(preMileage);
                                maintenanceAppInfoNowNumber.setText(nowMileage);
                                maintenanceAppInfoFixDescription.setText(explanation);
                                if (isTemp) {
                                    maintenanceAppInfoIsTemp.setText("√ 暂支");
                                } else {
                                    maintenanceAppInfoIsTemp.setText("X 不暂支");
                                }
                                if (isFree) {
                                    maintenanceAppInfoIsCost.setText("√ 有费用");
                                } else {
                                    maintenanceAppInfoIsCost.setText("X 无费用");
                                }

                                for (MaintenanceOrderInfo.DataBean.PersonListBean personListBean : personListBeans) {
                                    View view = LayoutInflater.from(mActivity).inflate(R.layout.fragment_maintenance_tab_item, null, false);
                                    LinearLayout tab = view.findViewById(R.id.maintenance_tab_Item);
                                    TextView project = view.findViewById(R.id.maintenance_tab_project);
                                    TextView projectTime = view.findViewById(R.id.maintenance_tab_projectTime);
                                    TextView projectCost = view.findViewById(R.id.maintenance_tab_projectCost);
                                    TextView projectCrash = view.findViewById(R.id.maintenance_tab_projectCrash);
                                    String actionName = personListBean.getActionName();
                                    String workTime = personListBean.getWorkTime() + "";
                                    String cost = getDecimal(personListBean.getCost().doubleValue());
                                    String totalCost = getDecimal(personListBean.getTotalCost().doubleValue());
                                    project.setText(actionName);
                                    projectTime.setText(workTime);
                                    projectCost.setText(cost);
                                    projectCrash.setText(totalCost);
                                    maintenanceFixOrderCheckOrder.addView(tab);
                                }

                                maintenanceAcceptanceUserDepart.setText(checkUserObjectBean.getDepartmentName());
                                maintenanceAcceptanceConfirmPeople.setText(checkUserObjectBean.getUserName());

                                maintenanceRemarkRemarkContent.setText(dataBean.getRemark());

                                String budgetInfo = budgetItemObjectBean.getBudgetInfo();
                                String allMoney = getDecimal(budgetItemObjectBean.getAllMoney().doubleValue());
                                String reimbursedMoney = getDecimal(budgetItemObjectBean.getReimbursedMoney().doubleValue());
                                String reimbursingMoney = getDecimal(budgetItemObjectBean.getReimbursingMoney().doubleValue());
                                String remainReimburseMoney = getDecimal(budgetItemObjectBean.getRemainReimburseMoney().doubleValue());
                                String applyedMoney = getDecimal(budgetItemObjectBean.getApplyedMoney().doubleValue());
                                String applyingMoney = getDecimal(budgetItemObjectBean.getApplyingMoney().doubleValue());
                                String remainApplyMoney = getDecimal(budgetItemObjectBean.getRemainApplyMoney().doubleValue());
                                maintenanceOtherCostFixCost.setText(String.format(
                                        forMat,
                                        budgetInfo,
                                        allMoney,
                                        reimbursedMoney,
                                        reimbursingMoney,
                                        remainReimburseMoney,
                                        applyedMoney,
                                        applyingMoney,
                                        remainApplyMoney
                                ));
                            } else {
                                ToastUtils.onErrorShowToast("登录态与服务器不一致");
                                initLogoutInfo(mActivity, userName);
                            }
                        } else {
                            ToastUtils.onErrorShowToast("该订单暂无详细信息");
                        }
                    }

                    @Override
                    public void fail(String errorMsg) {
                        ToastUtils.onErrorShowToast(errorMsg);
                    }
                });
    }
}
